<template>
  <div class="order-management">
    <n-card title="订单管理" :bordered="false" size="small" class="h-full shadow-sm rounded-8px">
      <!-- 搜索区域 -->
      <n-space class="pb-12px" justify="space-between">
        <n-space>
          <n-input
            v-model:value="searchParams.keyword"
            placeholder="搜索订单号或用户手机号"
            clearable
            class="w-240px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <icon-park-outline-search class="text-16px" />
            </template>
          </n-input>
          <n-select
            v-model:value="searchParams.status"
            placeholder="订单状态"
            clearable
            class="w-120px"
            :options="statusOptions"
          />
          <n-select
            v-model:value="searchParams.quota_type"
            placeholder="额度类型"
            clearable
            class="w-120px"
            :options="quotaTypeOptions"
          />
          <n-date-picker
            v-model:value="searchParams.dateRange"
            type="daterange"
            placeholder="下单时间范围"
            clearable
            class="w-240px"
          />
          <n-button type="primary" @click="handleSearch">搜索</n-button>
          <n-button @click="handleReset">重置</n-button>
        </n-space>
        <n-space>
          <n-button @click="handleExport">
            <template #icon>
              <icon-park-outline-download />
            </template>
            导出数据
          </n-button>
        </n-space>
      </n-space>

      <!-- 统计卡片 -->
      <n-grid :cols="5" :x-gap="16" class="mb-16px">
        <n-grid-item>
          <n-statistic label="总订单数" :value="statistics.total" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="待支付" :value="statistics.pending" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="已支付" :value="statistics.paid" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="已取消" :value="statistics.cancelled" />
        </n-grid-item>
        <n-grid-item>
          <n-statistic label="总金额" :value="statistics.totalAmount">
            <template #prefix>¥</template>
          </n-statistic>
        </n-grid-item>
      </n-grid>

      <!-- 表格 -->
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-key="(row) => row.id"
        remote
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </n-card>

    <!-- 订单详情弹窗 -->
    <n-modal v-model:show="detailVisible" preset="dialog" title="订单详情" class="w-1000px">
      <div v-if="currentOrder" class="space-y-16px">
        <!-- 基本信息 -->
        <n-descriptions :column="2" bordered>
          <n-descriptions-item label="订单号">
            {{ currentOrder.order_no }}
          </n-descriptions-item>
          <n-descriptions-item label="用户手机号">
            {{ currentOrder.user?.phone }}
          </n-descriptions-item>
          <n-descriptions-item label="订单状态">
            <n-tag :type="getStatusType(currentOrder.status)">
              {{ getStatusText(currentOrder.status) }}
            </n-tag>
          </n-descriptions-item>
          <n-descriptions-item label="额度类型">
            <n-tag>{{ getQuotaTypeText(currentOrder.quota_type) }}</n-tag>
          </n-descriptions-item>
          <n-descriptions-item label="目标">
            {{ currentOrder.domain?.name || currentOrder.expert?.nickname || '通用' }}
          </n-descriptions-item>
          <n-descriptions-item label="购买次数">
            {{ currentOrder.purchase_count }}
          </n-descriptions-item>
          <n-descriptions-item label="支付金额">
            ¥{{ currentOrder.amount }}
          </n-descriptions-item>
          <n-descriptions-item label="支付方式">
            {{ currentOrder.payment_method || '-' }}
          </n-descriptions-item>
          <n-descriptions-item label="外部订单号">
            {{ currentOrder.external_order_no || '-' }}
          </n-descriptions-item>
          <n-descriptions-item label="下单时间">
            {{ formatTime(currentOrder.created_at) }}
          </n-descriptions-item>
          <n-descriptions-item label="支付时间">
            {{ formatTime(currentOrder.paid_at) }}
          </n-descriptions-item>
          <n-descriptions-item label="过期时间">
            {{ formatTime(currentOrder.expires_at) }}
          </n-descriptions-item>
        </n-descriptions>
      </div>
      <template #action>
        <n-space>
          <n-button @click="detailVisible = false">关闭</n-button>
          <n-button 
            v-if="currentOrder?.status === 'pending'" 
            type="warning" 
            @click="handleMarkPaid(currentOrder)"
          >
            标记为已支付
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import { NButton, NTag, NSpace, useMessage, useDialog } from 'naive-ui'
import { formatTime } from '@/utils/time'
import { orderApi } from '@/service/api/bizhi'
import { useRoute } from 'vue-router'

const message = useMessage()
const dialog = useDialog()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const detailVisible = ref(false)
const tableData = ref([])
const currentOrder = ref(null)

// 搜索参数
const searchParams = reactive({
  keyword: '',
  status: null,
  quota_type: null,
  dateRange: null,
  page: 1,
  limit: 20
})

// 统计数据
const statistics = reactive({
  total: 0,
  pending: 0,
  paid: 0,
  cancelled: 0,
  totalAmount: 0
})

// 状态选项
const statusOptions = [
  { label: '待支付', value: 'pending' },
  { label: '已支付', value: 'paid' },
  { label: '已取消', value: 'cancelled' },
  { label: '已退款', value: 'refunded' }
]

// 额度类型选项
const quotaTypeOptions = [
  { label: '通用额度', value: 'general' },
  { label: '领域额度', value: 'domain' },
  { label: '专家额度', value: 'expert' }
]

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 20,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100]
})

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap = {
    pending: 'warning',
    paid: 'success',
    cancelled: 'error',
    refunded: 'info'
  }
  return typeMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    pending: '待支付',
    paid: '已支付',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return textMap[status] || status
}

// 获取额度类型文本
const getQuotaTypeText = (type: string) => {
  const textMap = {
    general: '通用额度',
    domain: '领域额度',
    expert: '专家额度'
  }
  return textMap[type] || type
}

// 表格列配置
const columns: DataTableColumns = [
  { title: 'ID', key: 'id', width: 80 },
  { title: '订单号', key: 'order_no', width: 180 },
  { title: '用户手机号', key: 'user.phone', width: 120 },
  {
    title: '订单状态',
    key: 'status',
    width: 100,
    render: (row: any) => {
      return h(NTag, {
        type: getStatusType(row.status)
      }, {
        default: () => getStatusText(row.status)
      })
    }
  },
  {
    title: '额度类型',
    key: 'quota_type',
    width: 100,
    render: (row: any) => {
      return h(NTag, {}, {
        default: () => getQuotaTypeText(row.quota_type)
      })
    }
  },
  { 
    title: '目标', 
    key: 'target', 
    width: 120,
    render: (row: any) => {
      return row.domain?.name || row.expert?.nickname || '通用'
    }
  },
  { title: '购买次数', key: 'purchase_count', width: 100 },
  { 
    title: '支付金额', 
    key: 'amount', 
    width: 100,
    render: (row: any) => `¥${row.amount}`
  },
  {
    title: '下单时间',
    key: 'created_at',
    width: 180,
    render: (row: any) => formatTime(row.created_at)
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    render: (row: any) => {
      return h(NButton, {
        size: 'small',
        type: 'primary',
        onClick: () => handleViewDetail(row)
      }, { default: () => '查看详情' })
    }
  }
]

// 获取统计数据
const fetchStatistics = async () => {
  try {
    const response = await orderApi.getOrderStats()
    if (response.code === 200) {
      Object.assign(statistics, response.data)
    } else {
      message.error(response.message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    message.error('获取统计数据失败')
  }
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: searchParams.page,
      limit: searchParams.limit,
      keyword: searchParams.keyword || undefined,
      status: searchParams.status || undefined,
      quota_type: searchParams.quota_type || undefined
    }

    // 处理日期范围
    if (searchParams.dateRange && searchParams.dateRange.length === 2) {
      params.start_date = new Date(searchParams.dateRange[0]).toISOString().split('T')[0]
      params.end_date = new Date(searchParams.dateRange[1]).toISOString().split('T')[0]
    }

    const response = await orderApi.getOrderList(params)
    if (response.code === 200) {
      tableData.value = response.data.list || []
      pagination.itemCount = response.data.pagination?.total || 0
      pagination.page = response.data.pagination?.page || 1
      pagination.pageSize = response.data.pagination?.limit || 20
    } else {
      message.error(response.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    message.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleViewDetail = (row: any) => {
  currentOrder.value = row
  detailVisible.value = true
}

// 标记为已支付
const handleMarkPaid = (order: any) => {
  dialog.warning({
    title: '确认操作',
    content: `确定要将订单"${order.order_no}"标记为已支付吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        // TODO: 调用API标记为已支付
        order.status = 'paid'
        order.paid_at = new Date().toLocaleString()
        message.success('订单已标记为已支付')
        detailVisible.value = false
        fetchData()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

// 导出数据
const handleExport = async () => {
  try {
    // TODO: 调用导出API
    message.success('导出成功')
  } catch (error) {
    message.error('导出失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置
const handleReset = () => {
  Object.assign(searchParams, {
    keyword: '',
    status: null,
    quota_type: null,
    dateRange: null,
    page: 1,
    limit: 20
  })
  fetchData()
}

// 分页变化
const handlePageChange = (page: number) => {
  pagination.page = page
  searchParams.page = page
  fetchData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.page = 1
  searchParams.limit = pageSize
  searchParams.page = 1
  fetchData()
}

onMounted(() => {
  // 处理URL查询参数
  const { user_phone } = route.query
  if (user_phone) {
    searchParams.keyword = user_phone as string
    message.info(`正在显示用户 ${user_phone} 的订单`)
  }

  fetchStatistics()
  fetchData()
})
</script>

<style scoped>
.order-management {
  height: 100%;
}
</style>
